var masterRateItemsARArray;
var masterRateItemsAPArray;
var masterRateCodesARArray;
var masterRateCodesAPArray;
var timset=0;
var popup=false;
var initgetMasterRateTable=false;
function clearerrmsg(element){
  $(element).text("").removeClass("ui-state-highlight");
  timset=0;
}
var newRateItemsList=new Array();  
/* $("#idAddRateItem").click(function(event) {
        	
        	
        		  event.preventDefault();
        		  
        });*/
        
 (function($){

     $.fn.quiggleDynamicFormAdd = function (templateBlock, placeHolder, indexBlock){
        $(this).click(function(){
        	var template = $(templateBlock);
            var indexField = $(indexBlock);
            var index = parseInt(indexField.text());
            var templateClone = template.clone();
            templateClone.html(templateClone.html().replace(/{index}/g, index));
			
            templateClone.attr('id', template.attr('id') + '-' + index)
            templateClone.removeClass('template');
            templateClone.insertBefore($(placeHolder));
			templateClone.bindProfileEvents();
            indexField.text(index + 1);
			var firstInput = $(":input:not(input[type=button],input[type=submit],button):visible:first", templateClone);
			firstInput.focus();
        });
		 

    };

    $.fn.quiggleDynamicRateItemAdd = function (templateBlock, placeHolder, indexBlock){
		
         $(this).click(function(){
            var template = $(templateBlock);
            var indexField = $(indexBlock);
            var index = parseInt(indexField.text());
            var templateClone = template.clone();
            templateClone.html(templateClone.html().replace(/{index}/g, index));
			templateClone.html(templateClone.html().replace(/rtindexcheck-temp/g, "rtindexcheck"));
			templateClone.html(templateClone.html().replace(/checkboxTax-temp/g, "checkboxTax"));
			templateClone.html(templateClone.html().replace(/checkboxReim-temp/g, "checkboxReim"));
            templateClone.attr('id', template.attr('id') + '-' + index)
            templateClone.removeClass('template');
            //templateClone.insertBefore($(placeHolder));
           // templateClone.bindProfileEvents();
		   $('#rateItemTable').find("tr:eq(0)").after(templateClone.find('tbody').html());
		    $('#rateItemTable').find("tr:eq(0)").next().find("input:eq(2)").focus();

            indexField.text(index + 1);
        });
    };
$.fn.bindProfileEvents = function(){
	$(this).find('.delete-button').each(function(){
		$(this).click(function(){
			var template = $(this).attr("template");
			 
			if (confirm("Are you sure you want to delete?")) {
				$(this).parent().find('.delete-input').val('true');
				$('#'+template).hide();
				/*var templateStr=template.split("-");
				
				if(templateStr[0]=="payPeriodTemplate")
					checkPayPeriodDuplicates();*/
			}
		})
	});
};
	


$.fn.RateTableCustomValidatorPhone=function(validatestring,submit,form){
		var flag = false;
	var flagInc = 0;
	var numbererrorstr='<div class="ketchup-errorPar"><div class="ketchup-error" style="width:125px;"><ul><li>Enter Valid Phone Number.</li></ul><span></span></div></div>'
  
	if($(form).find(this).length>0 && submit){
$(form).find(this).each(function(i){
	
	flag=isPhoneValid($(form).find(this).val());
	
	if(!flag){$(this).parent().find(".ketchup-errorPar").remove();$(this).before(numbererrorstr);flagInc++;$(this).focus();}
	else {$(this).parent().find(".ketchup-errorPar").remove();
	}
	});
		
	if(flagInc > 0)
		retflag = false;
	else 
	retflag = true;

	}  
	$(this).live("blur",function(){
	retflag=isPhoneValid($(this).val());
	
		if (!retflag){$(this).parent().find(".ketchup-errorPar").remove();$(this).before(numbererrorstr);}
	else{$(this).parent().find(".ketchup-errorPar").remove();}
	});

	return retflag;
	}; 
		
	
	
	

$.fn.RateTableCustomValidatorZip=function(validatestring,submit,form){
		var flag = false;
	var flagInc = 0;
	var numbererrorstr='<div class="ketchup-errorPar"><div class="ketchup-error"><ul><li>Enter Valid ZIP CODE.</li></ul><span></span></div></div>'
  
	if($(form).find(this).length>0 && submit){
$(form).find(this).each(function(i){
	
	flag=zipcodevalidation($(form).find(this).val());
	
	if(!flag){$(this).parent().find(".ketchup-errorPar").remove();$(this).before(numbererrorstr);flagInc++;$(this).focus();}
	else {$(this).parent().find(".ketchup-errorPar").remove();
	}
	});
		
	if(flagInc > 0)
		retflag = false;
	else 
	retflag = true;

	}  
	$(this).live("blur",function(){
	retflag=zipcodevalidation($(this).val());
	
		if (!retflag){$(this).parent().find(".ketchup-errorPar").remove();$(this).before(numbererrorstr);}
	else{$(this).parent().find(".ketchup-errorPar").remove();}
	});

	return retflag;
	}; 
	

	 $.fn.quiggleDynamicMasterRowAdd = function (templateBlock, placeHolderPrefix, indexBlock){
        $(this).click(function(){
            alert("add address click " + templateBlock);
            var template = $(templateBlock);
            var indexField = $(indexBlock);
            var index = parseInt(indexField.text());
            var templateClone = template.clone();
            templateClone.html(templateClone.html().replace(/{index}/g, index));
            var placeHolderId = placeHolderPrefix + (index-1);
            templateClone.attr('id', placeHolderPrefix + index)
//            templateClone.removeClass('template');
            templateClone.insertAfter($(placeHolderId));
            indexField.text(index + 1);
            templateClone.bindJobEvents();
            var focusField = templateClone.find("[name='rateItem[" + index +"].itemCode']");
            focusField.focus();
        });
    };

	
})(jQuery);

function quiggleCheckBoxtoggleSelect(toggleCheckboxesClass, IndCheckboxClass){
		$(toggleCheckboxesClass).click(function(){
		$(IndCheckboxClass).attr("checked",$(this).is(":checked"));
		});};


retflag=false;

$.fn.RateTableCustomValidator=function(validatestring,submit,form){
		var flag = false;
	var flagInc = 0;
	var Requirederrorstr='<div class="ketchup-errorPar"><div class="ketchup-error"><ul><li>This Field is Required.</li></ul><span></span></div></div>'
 
	if($(form).find(this).length>0 && submit){

		$(form).find(this).each(function(i){

	   flag=requiredfieldvalidtion($(this).val());	
	   
	if(!flag){$(this).parent().find(".ketchup-errorPar").remove();$(this).before(Requirederrorstr);
	flagInc++;$(this).focus();}
	else {$(this).parent().find(".ketchup-errorPar").remove();
	
	}
	});

	if(flagInc > 0)
		retflag = false;
	else 
	retflag = true;

	}  
	$(this).live("blur",function(){
	retflag=requiredfieldvalidtion($(this).val());
	if (!retflag){$(this).parent().find(".ketchup-errorPar").remove();$(this).before(Requirederrorstr);}
	else{$(this).parent().find(".ketchup-errorPar").remove();}
	});

	return retflag;
	}; 

$.fn.RateTableCustomValidatorNum=function(validatestring,submit,form){
		var flag = false;
	var flagInc = 0;
	var numbererrorstr='<div class="ketchup-errorPar"><div class="ketchup-error"><ul><li>Enter Numeric Value.</li></ul><span></span></div></div>'
    
	if($(form).find(this).length>0 && submit){
$(form).find(this).each(function(i){
	
	flag=numberfieldvalidtion($(this).val());
	
	if(!flag){$(this).parent().find(".ketchup-errorPar").remove();$(this).before(numbererrorstr);flagInc++;$(this).focus();}
	else {$(this).parent().find(".ketchup-errorPar").remove();
	}
	});
		
	if(flagInc > 0)
		retflag = false;
	else 
	retflag = true;

	}    
	$(this).live("blur",function(){
	retflag=numberfieldvalidtion($(this).val());
		if (!retflag){$(this).parent().find(".ketchup-errorPar").remove();$(this).before(numbererrorstr);}
	else{$(this).parent().find(".ketchup-errorPar").remove();}
	});

	return retflag;
	}; 

$.fn.RateTableCustomValidatorurl=function(validatestring,submit,form){
		var flag = false;
	var flagInc = 0;
	var numbererrorstr='<div class="ketchup-errorPar"><div class="ketchup-error"><ul><li>Enter Valid URL.</li></ul><span></span></div></div>'
  
	if($(form).find(this).length>0 && submit){
$(form).find(this).each(function(i){
	
	flag=validWebsiteUrl($(form).find(this).val());
	
	if(!flag){$(this).parent().find(".ketchup-errorPar").remove();$(this).before(numbererrorstr);flagInc++;$(this).focus();}
	else {$(this).parent().find(".ketchup-errorPar").remove();
	}
	});
		
	if(flagInc > 0)
		retflag = false;
	else 
	retflag = true;

	}  
	$(this).live("blur",function(){
	retflag=validWebsiteUrl($(this).val());
		if (!retflag){$(this).parent().find(".ketchup-errorPar").remove();$(this).before(numbererrorstr);}
	else{$(this).parent().find(".ketchup-errorPar").remove();}
	});

	return retflag;
	}; 


$.fn.RateTableCustomValidatoremail=function(validatestring,submit,form){
		var flag = false;
	var flagInc = 0;
	var numbererrorstr='<div class="ketchup-errorPar"><div class="ketchup-error"><ul><li>Enter valid email</li></ul><span></span></div></div>'
   	
	if($(form).find(this).length>0 && submit){
$(form).find(this).each(function(i){
	
	flag=isEmailValid($(form).find(this).val());
	
	if(!flag){$(this).parent().find(".ketchup-errorPar").remove();$(this).before(numbererrorstr);flagInc++;$(this).focus();}
	else {$(this).parent().find(".ketchup-errorPar").remove();
	}
	});
		
	if(flagInc > 0)
		retflag = false;
	else 
	retflag = true;

	}  
	$(this).live("blur",function(){
	retflag=isEmailValid($(this).val());
		if (!retflag){$(this).parent().find(".ketchup-errorPar").remove();$(this).before(numbererrorstr);}
	else{$(this).parent().find(".ketchup-errorPar").remove();}
	});

	return retflag;
	};

	function requiredfieldvalidtion(eleVal){
		var flag=false;
		if(eleVal=="")
			flag=false;
		else
			flag=true;
			
		return flag;
		}


	function numberfieldvalidtion(eleVal){
		
		if(isNaN(eleVal))
		{
		return false;
		}
		return true;	
	}


	function validWebsiteUrl(eleVal) {
			
	var pattern = /[a-z0-9-\.]+\.[a-z]{2,4}\/?([^\s<>\#%"\,\{\}\\|\\\^\[\]`]+\.[A-Z]{2,4}$)?$/i;
	if(eleVal == '')		
		{
			return true;
		}
	else if (pattern.test(eleVal)) {
           
        return true;
		
		} 
            
        return false;


	}

		
	function isEmailValid(eleVal){
		var flag=false;
	  var emailRegEx = /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{1,8}$/i;
	  if(eleVal == '')
		{
		 flag =true;
		}
		
	   else if (emailRegEx.test(eleVal))
		{	
		flag =true;
		}
			 
		return flag;
		 
	
		
	}
	

	function zipcodevalidation(eleVal){
		var flag=false;
		var value =eleVal.replace(/^\s+|\s+$/g,"");
		var zipcode_regex = /^\d{5}$/;
		//var zip_canada=/^[a-zA-Z]\d{1}[a-zA-Z](\-| |)\d{1}[a-zA-Z]\d{1}$/;
		var zip_canada=/^[a-z][0-9][a-z]\s*?[0-9][a-z][0-9]$/i;
		var zipUS=/^(\d{5})(-\d{4})?$/;
		
		if(value=="")
			flag=true;
		else if(zipcode_regex.test(value))
			flag=true;
		else if(zip_canada.test(value))
			flag=true;
			else if(zipUS.test(value))
			flag=true;
			
			
		return flag;
		}

 function isPhoneValid(eleVal){
		var flag=false;
        var phone1=/^\(?[0-9]{0,9}?[-.()+\s]?([0-9]{0,9})\)?[-.()\s]?([0-9]{0,9})[-.()\s]?([0-9]{0,8})$/;
        var value =eleVal .replace(/([\s.?*+^$[\]!\\/\'@\"(){}-])/g, "");

        if(value=="")
         flag=true;

        else if(value.length > 9 && value.length < 16 && !isNaN(value))
        flag=true;

     return flag;

  }
	
function closesuccessdiv(){
   $('#successDiv').hide();
}
function closeErrmsg(){
	$("#ui-tips").html('');
}
$(document).ready(function(){
	
	$(".deleteRateProfile").click(function(){
		 if (confirm("Are you sure, you want to delete this Rate Profile?")) {
			var profileType = $("#profileType option:selected").val();
			var entityUserId = $("#entityUserUserId").val();
			 if(!(entityUserId != null && $.trim(entityUserId).length > 0))
				 entityUserId = 0;
			   $.ajaxSetup({
				   jsonp: null,
				   jsonpCallback: null
				});

			    $.ajax({
				  type:'POST',
				  url: 'rate-template.action?removeRateTable',
				  dataType: 'json',
				  data: {entityUserId:entityUserId,rateProfileTypeId:profileType},
				  success: function(result){
					  if(result){
						  window.location = "rate-template.action";
					  }
					  else{
						  $("#ui-tips").html('<div class="alert alert-success" id="successDiv"><b>This Profile is used in Working Jobs, You cannot remove this Profile.</b></div>');
						  $('html, body').animate({ scrollTop: $("#ui-tips").offset().top }, "slow");
						  setTimeout("closeErrmsg()",12000);
					  }
		 
				 },
				  error:function() { 
					  
				  }
			});
		   }	
		});
$(".job-start").change(function(){
		
	if($(this).val() != null && $.trim($(this).val()).length == 0)
	$(".ketchup-error").remove();
		
	});
$(".job-start").blur(function(){
	
	if($(this).val() != null && $.trim($(this).val()).length == 0)
	$(".ketchup-error").remove();
		
	});

	/*$("#infoContainer").css({marginRight:"-1000px"});
	   $("#infoContainer").width("0px");
	   $("#qglRTinfoContainer").css({marginRight:"-1000px"});
	   $("#qglRTinfoContainer").width("0px");
	   
		  $(function () {
         $("#infoclose").click(function () {
				 $("#infoContainer").width("0px")
            $("#infoContainer").animate({marginRight:"-1000px"},1000);
           //$("#helpIMG").css("display","block");
			//$("#qglRTinfoIMG").css("display","block");
         });
         $("#infoButton").click(function () {
				 $("#infoContainer").width("400px")
			      $("#infoContainer").animate({marginRight:"0px"},500);
				 	//$("#helpIMG").css("display","none");
				//$("#qglRTinfoIMG").css("display","none");
			});
         
         $("#qglRTinfoclose, #qglRTslidebutton1").click(function () {
			 $("#qglRTinfoContainer").width("0px")
        $("#qglRTinfoContainer").animate({marginRight:"-1000px"},1000);
       
     });
     $("#qglRTinfoButton").click(function () {
			 $("#qglRTinfoContainer").width("400px")
		      $("#qglRTinfoContainer").animate({marginRight:"0px"},500);
			 
		});
         
         
         
      });*/
	   $(".rate-item-val").live("blur",function(){
		   values=($(this).val()).split('.');
			one=values[0];
			two=values[1];
			
			var num = one;
			var one1 = num.toString();
			one1 = one1.replace(/^0+/,'');
			
			if(one=='' && two == '' ){ 
				
				var num=0;
				$(this).val(num.toFixed(2));
				return false;
			}
			
			var value1 = $.trim(($(this).val()));
			if(value1=='' || value1 == 0 ){ 
				
				var num=0;
				$(this).val(num.toFixed(2));
				return false;
			}
			
			var precisionflag=isNaN(one)?false:true;
			var scaleflag=isNaN(two)?false:true;
					
			if(!precisionflag){ 
				var num=0;
				$(this).val(num.toFixed(2));
			}
			else if(!scaleflag){
				var num=parseInt(one1,10).toFixed(2);
				$(this).val(num);
			}
			else if(values.length>1){
				if(!scaleflag && precisionflag)
				{
				var num=one;
				$(this).val(num.toFixed(2));
				}
				else if(scaleflag){
			   	var numaddO = one1+"."+two;
				var num=roundNumber(numaddO,2);
				
				if(!isNaN(num.toString().split(".")[1]))
				{
				var numaddO =  num.toString().split(".")[1].length==1?one1+"."+num.toString().split(".")[1]+"0":num;
				//alert(numaddO);
				$(this).val(numaddO);
				}
				else{
				var num=parseInt(numaddO,10).toFixed(2);
				$(this).val(num);
				}
				}
				
			}
					
			
		});
		function roundNumber(num, dec) {
		var result = Math.round(num*Math.pow(10,dec))/Math.pow(10,dec);
		return result;
		}
    $(".rate-item-val").live("keyup",function(){		
		$(this).prev().val($(this).val());
		
	});
		/*console.log("hello");
		ajaxCallToGetMasterRateItems(1);
		ajaxCallToGetMasterRateItems(2);*/
	
setTimeout("closesuccessdiv()",5000);  

$("input").live("focusin",function(){
       $(this).closest(".userdetailsformcolum").find(".ketchup-errorPar").remove();
});

	
	currentAction = 1;
	
$(".friday-date-picker").live("focus", function(){	
		$(this).datepicker({
			
			  beforeShowDay: function(date){ 
			  var day = date.getDay(); 
			  return [day == 5,""];
			}
		});
    });
	
	$("#rateTableFormId :input").keypress(function() {
		if($(this).attr('id') != "save"){
		isRateTableChaned = true;
		isFormFieldChanged = true;
		}
		
	});
	
	$(".select-box").live("change",function(){
		
		isRateTableChaned = true;
		isFormFieldChanged = true;
	});
	
	
	$(".delete-button").click(function() {
		
		isRateTableChaned = true;
		isFormFieldChanged = true;
		
	});
	
   $(".add-button").click(function() {
		
		isRateTableChaned = true;
		isFormFieldChanged = true;
		
	});
   
   $("#idAddRateItem").click(function() {
		
		isRateTableChaned = true;
		isFormFieldChanged = true;
		
	});
   
   $('#riCheckBox-delete-spanId').click(function() {
		
		isRateTableChaned = true;
		isFormFieldChanged = true;
		
	});

$(".rateitembuttons .button").focusout(function(){
$(".rateitemform").attr("tabindex","0");
});
$(".rateitemform").focus(function(){

  setTimeout(function(){$("#idAddRateItem").focus()},300); 			
$(".rateitemform").removeAttr("tabindex");
});
	
	$('.code-name').live("change",function(){
	
		var uniqueCodeInd=checkDuplicateRateItemCodes();
	
		if(!uniqueCodeInd){
	    	$("#rate-item-err-div").text("This code already exists. Please choose from the master rate table or create a new code").addClass( "ui-state-highlight").css("margin", "65px 0 0");
	    	$("#rate-item-err-div").focus();
		}
	    else{
	    	$("#rate-item-err-div").text("").removeClass("ui-state-highlight");
	    	$(".errorHighlight").removeClass("errorHighlight");
	    	highlightCheckedRows();
	    
		var curcode=$(this);
		$(".modalratetable-pop .code-name").each(function(){
		  
		       if($(this).val().toLowerCase()==curcode.val().toLowerCase()){
			   $(curcode).closest("td").next().find("input").val($(this).closest("tr").find(".input-desc").val()); 
			   $(curcode).closest("tr").find(".numberVal").val($(this).closest("tr").find(".input-value").val()); 
			   $(curcode).closest("tr").find(".price-type-id").val($(this).closest("tr").find(".price-type-id").val());

			   $(curcode).closest("tr").find(".rate-item-list").val($(this).closest("tr").find(".rate-item-list ").val());
			   $(curcode).closest("tr").find("td:eq(6) :input").attr("checked",$(this).closest("tr").find(".checkboxReim-MR").is(":checked"));
		
			   $(curcode).closest("tr").find("td:eq(7) :input").attr("checked",$(this).closest("tr").find(".checkboxTax-MR").is(":checked"));
		  }
		});}
	});

//navigating without saving
var warnMessage = "You have unsaved changes on this page!";
 $('input:submit').click(function(e) {
         window.onbeforeunload = null;
    });

    $('input:not(:button,:submit),textarea,select,checkbox').bind("change keypress",function () {
        window.onbeforeunload = function () {
		 if (warnMessage != null && !popup && isRateTableChaned) return warnMessage;
        }
    });
	 $('.applybutton').click(function(e) {
		 window.onbeforeunload = null;
        warnMessage = null;
    });
	
	 $('#applybutton').click(function(e) {
		 window.onbeforeunload = null;
        warnMessage = null;
    });
	
	/*$('.public-private-button').click(function(e){
		
		 window.onbeforeunload = function () {
            if (warnMessage != null) return warnMessage;
        }
	});
    $('input:submit').click(function(e) {
        warnMessage = null;
    });


//end of navigating without saving*/
//$("#profileCategory").focus();
$("#initials").blur(function(){
$("#rateTblInitials").html($("#initials").val());		
});
$(".mandatoryfield").RateTableCustomValidator("required",false);
$(".numberVal").RateTableCustomValidatorNum("number",false);
$(".urlinput").RateTableCustomValidatorurl("url",false);
$(".emailval").RateTableCustomValidatoremail("email",false);
$("#zip").RateTableCustomValidatorZip("zip",false);
$(".phoneval").RateTableCustomValidatorPhone("Phone",false);


$(".payday").live("change",function(){
	//checkPayPeriodDuplicates();
});

$(".turnInOther").live("change",function(){
	//checkPayPeriodDuplicates();
});


	/*$(".mandatoryfield").attr("data-validate","validate(required)");
	$(".emailval").customValidator("validate(email)");
	$(".urlinput").customValidator("validate(curl)");
	$(".numberVal").customValidator("validate(price)");
		
		$("form").ketchup();*/
	
	
	$(".userRateItems .code-name").live("change", function(){
		refreshExpediteOptionsList();	
	});
	
	
	//$(".expedite-rate-item-list").hide();
    $(".userRateItems .price-type-id").live("change",function(){
		if($(this).val()==1){
			 $(this).closest("tr").find(".rate-item-list").empty();
			 for(var k = 0 ; k < perunitlist.length ; k++){
				 $(this).closest("tr").find(".rate-item-list").append("<option value='"+perunitlist[k].id+"'>"+perunitlist[k].type+"</option>");
	           }
		}
		refreshExpediteOptionsList();
	});	
	

var timeZoneArray = ["A","ADT","AFT","AKDT","AKST","ALMT","AMST","AMT","ANAST","ANAT",
		"AQTT","ART","AST","AZOST","AZOT","AZST","AZT","B","BNT","BOT","BRST","BRT","BST",
		"BTT","C","CAST","CAT","CCT","CDT","CEST","CET","CHADT","CHAST","CKT","CLST",
		"CLT","COT","CST","CVT","CXT","ChST","D","DAVT","E","EASST","EAST","EAT","ECT",
		"EDT","EEST","EET","EGST","EGT","EST","ET","F","FJST","FJT","FKST","FKT","FNT",
		"G","GALT","GAMT","GET","GFT","GILT","GMT","GST","GYT","H","HAA","HAC","HADT","HAE",
		"HAP","HAR","HAST","HAT","HAY","HKT","HLV","HNA","HNC","HNE","HNP","HNR","HNT","HNY",
		"HOVT","I","ICT","IDT","IOT","IRDT","IRKST","IRKT","IRST","IST","JST","K","KGT",
		"KRAST","KRAT","KST","KUYT","L","LHDT","LHST","LINT","M","MAGST","MAGT","MART",
		"MAWT","MDT","MESZ","MEZ","MHT","MMT","MSD","MSK","MST","MUT","MVT","MYT",
		"N","NCT","NDT","NFT","NOVST","NOVT","NPT","NST","NUT","NZDT","NZST",
		"O","OMSST","OMST","P","PDT","PET","PETST","PETT","PGT","PHOT","PHT",
		"PKT","PMDT","PMST","PONT","PST","PT","PWT","PYST","PYT","Q","R","RET",
		"S","SAMT","SAST","SBT","SCT","SGT","SRT","SST","T","TAHT","TFT","TJT",
		"TKT","TLT","TMT","TVT","U","ULAT","UYST","UYT","UZT","V","VET","VLAST",
		"VLAT","VUT","W","WAST","WAT","WDT","WEST","WEST","WESZ","WET","WEZ","WFT",
		"WGST","WGT","WIB","WIT","WITA","WST","WST","WST","WT","X","Y","YAKST",
		"YAKT","YAPT","YEKST","YEKT","Z"];


 $("#timeZone").live("focus", function(){

	$("#timeZone").autocomplete({

	source: function(req, responseFn) {
        var re = $.ui.autocomplete.escapeRegex(req.term);
        var matcher = new RegExp( "^" + re, "i" );
        var a = $.grep( timeZoneArray, function(item,index){
            return matcher.test(item);
        });
        responseFn( a );
    }
});
}); 

$("#timeZone").autocomplete({
source: function(req, responseFn) {
        var re = $.ui.autocomplete.escapeRegex(req.term);
        var matcher = new RegExp( "^" + re, "i" );
        var a = $.grep( timeZoneArray, function(item,index){
            return matcher.test(item);
        });
        responseFn( a );
    }
});
	
 $("#masterratetable").click(function(){
	 var userItemCount=0;
	 var userRateItemsList=new Array();
	 showmasterdialog=true;
	 $(".userRateItems tbody tr").each(function(index){
		 if($(this).find(".code-name").val()=="" || $(this).find(".code-name").val()==undefined){
		
			
		 }
		 else{
			 userItemCount++;
			 userRateItemsList.push($(this).find(".code-name").val().toLowerCase());
		 }
		
		
		 
	 });
	 setMasterRateItemsList(userRateItemsList);
	 
   });
  
 	$( "#dialog-form" ).dialog({
				autoOpen: false,
				open:function(){
					
					$(".ui-button").addClass("ui-state-default");
					
				},
				height: 400,
				width: 940,
				modal: true,
				title:"Master Rate Table",
				buttons: {
					"Add Selected Items to Rate Table": function() {
					  $("#modalratetable .code-name").removeAttr("disabled");
					  $("#modalratetable .code-name").removeAttr("onfocus");
					  $("#modalratetable .code-name").removeAttr("readonly");
						$(".rtindexcheck-MR").each(function(){
							 if($(this).is(":checked")){
								 var htmstr=$(this).closest("tr");
								 quiggleDynamicMRItemAdd( htmstr, "#rateItem", "#ri-index");	
							 }
						  });
						refreshExpediteOptionsList();
							

						$( this ).dialog( "close" );
					},
					
				},
				close: function() {
					//allFields.val( "" ).removeClass( "ui-state-error" );
				},
				  create:function () {
				        $(this).closest(".ui-dialog")
				            .find(".ui-button"); // the first button
				           // .addClass("p-button");
				    }

			});
 	if($("#profileCategory").val() == '1'){
 		  $('#dialog-form').dialog( "option", "title", 'Master Rate Table A/R');
 	}else{
 		 $('#dialog-form').dialog( "option", "title", 'Master Rate Table A/P');
 	}
			
 	$( "#masterrate-dialog-form" ).dialog({
		autoOpen: false,
		height: 400,
		width: 940,
		modal: true,
		title:"Master Rate Table",
		close: function() {
			
		},
		  create:function () {
		       
		    }

	});			
			
			/*$(".numberVal").live("keypress",function(event) {
    var key = window.event ? event.keyCode : event.which;

    if (event.keyCode == 8 || event.keyCode == 46
     || event.keyCode == 37 || event.keyCode == 39 || event.keyCode == 9) {
        return true;
    }
    else if ( key < 48 || key > 57 ) {
        return false;
    }
    else return true;
}); */   

	/** number validations
	$(".numberVal").attr("pattern","^[0-9]+$");
	/** web-site url 
	$("#websiteurl").attr("pattern","(http|https)(:\/\/))?([a-zA-Z0-9]+[.]{1}){2}[a-zA-z0-9]+(\/{1}[a-zA-Z0-9]+)*\/?");

**/
 	
 	$(".rtindexcheck").live("click",function(){
 		if($(this).is(":checked"))
 			$(this).closest("tr").addClass('heighlight');
 		else
 			$(this).closest("tr").removeClass('heighlight');
 		
 	});

 $(this).find('.delete-button').each(function(){
	$(this).click(function(){
		var template = $(this).attr("template");
		 
		if (confirm("Are you sure you want to delete?")) {
			$(this).parent().find('.delete-input').val('true');
			$('#'+template).hide();
			/*var templateStr=template.split("-");
			
			if(templateStr[0]=="payPeriodTemplate")
				checkPayPeriodDuplicates();*/
		}
	})
});

	
$("#addContactAddress").quiggleDynamicFormAdd("#contactTemplate","#contactaddress-placeholder","#contactaddressIndex");
$("#addPayPrd").quiggleDynamicFormAdd("#payPeriodTemplate","#payPeriod-placeholder","#payPrdIndex");
$("#idAddRateItem").quiggleDynamicRateItemAdd("#rateItemTemplate", "#rate-item-placeholder", "#ri-index");

$(document).ready(function(){

showmasterdialog=false;

$("#masterratetable").click(function(){$("#modalratetable .code-name").attr("disabled","disabled");});
$("#rateTableFormId").live("focus",function(){
if(!initgetMasterRateTable){

	getMasterRateTable($("#profileCategory").val(),false);
previousSelectedtype=$("#profileCategory").val();
showmasterdialog=false;
count++;
initgetMasterRateTable=true;}
});
$("#profileCategory").change(function(){
previousSelectedtype=$(this).val();
getMasterRateTable($(this).val(),false);
showmasterdialog=false;
});

	$('#riCheckBox-delete-spanId').click(function(){
		
	
		var itemIds ='';
		var codeName;
		var codeValue;
		var errCount=0;
		var rateEmpty=false;
		var str='';
		var delErrFlag = true;

		var rateItemmsgDiv = document.getElementById("rateItemsuccessDiv");
		
		$(".rtindexcheck").each(function(){
			
			if($('.rtindexcheck').is(':checked') == true)
				delErrFlag = false;
			if($('.rtindexcheck').is(':checked') == false)
				delErrFlag = true;

		});
	
		if(delErrFlag)
		{
			$("#rateItemsuccessDiv").text("No rate code selected").addClass( "ui-state-highlight").css("margin", "65px 0 0");
			return;
		}
		else
		{
			$("#rateItemsuccessDiv").empty();
			$("#rateItemsuccessDiv").removeClass("ui-state-highlight");
		}

		$(".rtindexcheck").each(function(){
		
			if($('.rtindexcheck').is(':checked') == true)
			{
				
				if($(this).is(":checked")){
			 
				$("#rateItemsuccessDiv").empty();
			  $("#rateItemsuccessDiv").removeClass("ui-state-highlight");
	    	 if($('#rateItemId'+$(this).attr('id')).length>0){
	    		 codeValue=$('#rateItemId'+$(this).attr('id')).val();
	    		 if($(this).closest("tr").find(".code-name").val()=="")
	    			 rateEmpty=true;
	    	 }
	    	 else{
				
	    		 var codeId=$(this).closest("tr").find(".code-name").attr("id");
	    		 codeValue=-codeId;
	    	 }

	    	 $(".userRateItems tbody tr").each(function(index){
	    		 if(!rateEmpty){
	    			 if(!($(this).find(".rtindexcheck").is(":checked"))){
		    			 if($(this).find(".rate-item-list option:selected").val()==codeValue){
		    				 errCount++;
		    			 }
		    		 } 
	    		 } 
	    	 });
	    	 if(errCount==0){
	 	    	if($('#rateItemId'+$(this).attr('id')).val() == undefined || $('#rateItemId'+$(this).attr('id')).val() == 0 || $('#rateItemId'+$(this).attr('id')).val() == '0' || $.trim($('#rateItemId'+$(this).attr('id')).val()) == ''){	 	    		
			    	$('#rateItem'+$(this).attr('id')).val(true);
		    		$(this).closest("tr").remove();
				$("#rateItemsuccessDiv").empty();
			  $("#rateItemsuccessDiv").removeClass("ui-state-highlight");
					
	 	    	}
	 	    	else
	 	    	   itemIds = itemIds+$('#rateItemId'+$(this).attr('id')).val()+',';	    	 
	 	    	 
		  	}
	    	else{
	 	    	$("#rate-item-qgl-err-div").text("Selected rate item to be deleted has been applied as expedite. Please make sure that no dependency exists and then delete").addClass( "ui-state-highlight").css("margin", "65px 0 0");	
	 	    	$("#rate-item-qgl-err-div-bottom").text("Selected rate item to be deleted has been applied as expedite. Please make sure that no dependency exists and then delete").addClass( "ui-state-highlight");
	 	    	if(timset==0){
			    	 setTimeout('clearerrmsg("#rate-item-qgl-err-div")',5000);
			    	 setTimeout('clearerrmsg("#rate-item-qgl-err-div-bottom")',5000);
			    	 timset = 1;
			    }
	    	} 
		  }
		  }
		 
	  });
	  if($.trim(itemIds).length > 1)
	  {
		  itemIds = $.trim(itemIds);
		  itemIds = itemIds.slice(0,-1);
           if(itemIds.length > 0){
        	   
        	   $.ajaxSetup({
        		   jsonp: null,
        		   jsonpCallback: null
        		});


        	    $.ajax({
        		  type:'POST',
        		  url: 'rate-template.action?checkRateItems',
        		  dataType: 'json',
        		  data: {rateitems:itemIds},
        			 
        		  success: function(result){
        			  var notdelcodes = "";
        			  var notdelCodeArr=new Array();
        			  var notdel = false;
        			  $(".rtindexcheck").each(function(){
        				     if($(this).is(":checked")){ 
        				    	for(var i in result){
        				    	  if(result[i].rateItemId == $('#rateItemId'+$(this).attr('id')).val()){
        				    		  if(result[i].deleted){
        				    	         $('#rateItem'+$(this).attr('id')).val(true);    	 
        				    	         $(this).next().attr('id');
        						         $(this).closest("tr").remove();
        						         $("#rate-item-err-div").text("").removeClass("ui-state-highlight");
        				    		  }
        				    		  else{
        				    			  notdel = true; 
        				    			  notdelCodeArr.push($(this).closest("tr").find(".code-name").val());
        				    			 
        				    			  notdelcodes = notdelCodeArr.join(', ');
        				    		 }
        				    	  }
        				    	}
        					 }
        				     
        				  });
        			  if(notdel){
        			     $("#rate-item-qgl-err-div").text( "Selected rate item(s) "+notdelcodes+" in use for jobs in progress, cannot be deleted.").addClass( "ui-state-highlight").css("margin", "65px 0 0");
        			     $("#rate-item-qgl-err-div-bottom").text( "Selected rate item(s) "+notdelcodes+" in use for jobs in progress, cannot be deleted.").addClass( "ui-state-highlight");
        			     if(timset==0){
        			    	 setTimeout('clearerrmsg("#rate-item-qgl-err-div")',5000);
        			    	 setTimeout('clearerrmsg("#rate-item-qgl-err-div-bottom")',5000);
        			    	 timset = 1;
        			     }
        			  }
        		 },
        		  error:function() { 
        		
        		  }
        	});
        	   
           }
	  }
	 
		  if($("#rate-item-qgl-err-div").html()==""){
			  refreshExpediteOptionsList();
		  }
		 
		  if($("#rate-item-err-div").html()!=""){
			  var uniqueCodeInd=checkDuplicateRateItemCodes();
			    if(!uniqueCodeInd)
			    	$("#rate-item-err-div").text("This code already exists. Please choose from the master rate table or create a new code").addClass( "ui-state-highlight").css("margin", "65px 0 0");
			    else{    	
			    	$("#rate-item-err-div").text("").removeClass("ui-state-highlight");    	
			    	$(".errorHighlight").removeClass("errorHighlight");
			    	//highlightCheckedRows();
			    }
		  }
		  else
			  $(".errorHighlight").removeClass("errorHighlight"); 
		  
		 
			  
			  
		  
		 
		  $(".rtindexcheckAll").attr("checked",false);
	 });
});

// MR - Master Rate Table
quiggleCheckBoxtoggleSelect(".rtindexcheckAll", ".rtindexcheck");
quiggleCheckBoxtoggleSelect(".rtindexcheckAll-MR", ".rtindexcheck-MR");
quiggleCheckBoxtoggleSelect(".checkboxAllTax", ".checkboxTax");
quiggleCheckBoxtoggleSelect(".checkboxAllTax-MR", ".checkboxTax-MR");
quiggleCheckBoxtoggleSelect(".checkboxAllReim", ".checkboxReim");
quiggleCheckBoxtoggleSelect(".checkboxAllReim-MR", ".checkboxReim-MR");


	$("form").submit(function(){
		
  		$("#ui-tips").text("").removeClass("ui-state-highlight");
		
	$(".mandatoryfield").RateTableCustomValidator("required",true,this);
	var isPopup=false;
	retflag= validateRateTable();
		
	if(retflag)
	retflag = checkPayPeriodDuplicates(isPopup);

	if(retflag)
		retflag =checkForJobStartDate(isPopup);

	if(retflag)
		retflag = checkProfileCategoryDetails(isPopup);
	
	if(retflag)
	$(".numberVal").RateTableCustomValidatorNum("number",true,this);
	
	if(retflag)
	$(".urlinput").RateTableCustomValidatorurl("url",true,this);
	
	if(retflag)
	$(".emailval").RateTableCustomValidatoremail("email",true,this);
	if(retflag)
	$("#zip").RateTableCustomValidatorZip("zip",true,this);
	
	if(retflag)
	$("#mainPhone").RateTableCustomValidatorPhone("Phone",true,this);
		
	if(retflag) 
		warnMessage = null;
		
	return retflag;
    });
	
	
	$(".paydayother").live("change",function(){
		
		if ($(this).hasClass("payday")) {
			if($(this).val()==1)
				$(this).closest(".userdetailsformcolum").find('.job-start-date').removeClass("hidden");		
			else
				$(this).closest(".userdetailsformcolum").find('.job-start-date').addClass("hidden");
		}
	
	if($(this).val()==5){$(this).hide();$(this).closest(".userdetailsformcolum").find(".f-l").removeClass("hidden");}
	else{$(this).closest(".userdetailsformcolum").find(".f-l").addClass("hidden");}
		
	});

   $(".add-button, .delete-button, .p-button").attr("tabindex","0");
  var is_chrome = navigator.userAgent.toLowerCase().indexOf('chrome') > -1;
  if(is_chrome==true){
  
  $(".add-button, .delete-button, .p-button").live("keydown",function(event) {
  if (event.which == 32 ) {
 return false;
  }
  });
  
  $(".add-button, .delete-button, .p-button").live("keyup",function(event) {
	
  	if (event.which == 32 ) {
	$(this).trigger("click");
	}
    });
  }
  
  else{
   $(".add-button, .delete-button, .p-button").live("keypress",function(event) {
 
  if (event.which == 32 ) {
  event.preventDefault();
  $(this).trigger("click");
  }
  });
  }
   	$(".paydayother").each(function(){
   		
   		if ($(this).hasClass("payday")){   			
   		  if($(this).val()==1)   			  
			$(this).closest(".userdetailsformcolum").find('.job-start-date').removeClass("hidden");			
   		  else
   			  $(this).closest(".userdetailsformcolum").find('.job-start-date').addClass("hidden");
   		}
   		
   		
		
		if($(this).val()==5){$(this).hide();$(this).closest(".userdetailsformcolum").find(".f-l").removeClass("hidden");}
		else{$(this).closest(".userdetailsformcolum").find(".f-l").addClass("hidden");}
			
	});
 
});

function removeDuplicateElement(arrayName)
{
	var newArray=new Array();
	label:for(var i=0; i<arrayName.length;i++ )
	{  
	for(var j=0; j<newArray.length;j++ )
	{
	if(newArray[j]==arrayName[i]) 
	continue label;
	}
	newArray[newArray.length] = arrayName[i];
	}
	return newArray;
}

 		
        
function validateRateTable(){
	
	var uniqueCodeInd=checkDuplicateRateItemCodes();
    if(!uniqueCodeInd)
    	$("#rate-item-err-div").text("This code already exists. Please choose from the master rate table or create a new code").addClass( "ui-state-highlight").css("margin", "65px 0 0");
    else{    	
    	$("#rate-item-err-div").text("").removeClass("ui-state-highlight");    	
    	$(".errorHighlight").removeClass("errorHighlight");
    	highlightCheckedRows();
    }
   
    var uniqueProfileInd=true;
    var initials=$("#initials").val();
    var fullname=$("#fullName").val();
	var profileType=$("#profileType option:selected").val();
    if(!(initials==null || initials=="") && !(fullname==null || fullname=="")){
    	uniqueProfileInd=checkDuplicateRateProfile(initials, profileType);
    
  	    if(!uniqueProfileInd){
  	    	$("#ui-tips").text("Duplicate Rate Profile. Rate Profile already exists with same Profile Name and Initials").addClass( "ui-state-highlight" );
  	    	$('html, body').animate({ scrollTop: $("#ui-tips").offset().top }, "slow");

  	    }
  	    else
  	    	$("#ui-tips").text("").removeClass("ui-state-highlight");
    }
    
    var isMandatory = checkMandatory('#initials', 'Initials', false);
    isMandatory = checkMandatory("#fullName", "Full Name", true) && isMandatory ;
    isMandatory=uniqueCodeInd && isMandatory && uniqueProfileInd;        
    return isMandatory;
}


  function quiggleDynamicMRItemAdd (templateBlock, placeHolder, indexBlock){
   
										
	            var template = $(templateBlock);
				
				var indexField = $(indexBlock);
	            var index = parseInt(indexField.text());
				
	            var templateClone = template.clone();

				templateClone.find(":input:eq(0)").attr("name","rateTemplate.rateItemList[{index}].jobRateItem");
				templateClone.find(":input:eq(2)").attr("name","rateTemplate.rateItemList[{index}].codeName");
				templateClone.find(":input:eq(3)").attr("name","rateTemplate.rateItemList[{index}].rateItemDescription");
				templateClone.find(":input:eq(4)").attr("name","rateTemplate.rateItemList[{index}].rateItemValue");
				templateClone.find(":input:eq(5)").attr("name","rateTemplate.rateItemList[{index}].priceType");
				templateClone.find(":input:eq(6)").attr("name","rateTemplate.rateItemList[{index}].unitType");
				templateClone.find(":input:eq(7)").attr("name","rateTemplate.rateItemList[{index}].reimbursable");
				templateClone.find(":input:eq(8)").attr("name","rateTemplate.rateItemList[{index}].taxable");
				templateClone.find(":input:eq(4)").addClass("numberVal");

				templateClone.html(templateClone.html().replace(/{index}/g, index));
				templateClone.html(templateClone.html().replace(/rtindexcheck-MR/g, "rtindexcheck"));
				templateClone.html(templateClone.html().replace(/checkboxReim-MR/g, "checkboxReim"));
				templateClone.html(templateClone.html().replace(/checkboxTax-MR/g, "checkboxTax"));
				templateClone.html(templateClone.html().replace(/rateItem/g,"rateItem"));
				
	            //templateClone.attr('id', template.attr('id') + '-' + index)
	            templateClone.removeClass('template');
				
				templateClone.find(":input:eq(0)").attr("checked",false);
				templateClone.find(":input:eq(1)").val(template.find(":input:eq(1)").val());
				templateClone.find(":input:eq(2)").val(template.find(":input:eq(2)").val());
				templateClone.find(":input:eq(3)").val(template.find(":input:eq(3)").val());
				templateClone.find(":input:eq(4)").val(template.find(":input:eq(4)").val());
				templateClone.find(":input:eq(5)").val(template.find(":input:eq(5)").val());
				templateClone.find(":input:eq(6)").val(template.find(":input:eq(6)").val());
				templateClone.find(":input:eq(7)").val(template.find(":input:eq(7)").val());
		
					/*template.(":input").each(function(i){
					templateClone.html().find("input:eq("+i+")").val($(this).val());
					
					});*/
				//template.html(template.html().replace(/{index}/g, index));
	            //templateClone.insertBefore($(placeHolder));
				
				if($("#rateItemTable tr:last").find("input:eq(1)").val()!="" && $("#rateItemTable tr:last").find("input:eq(2)").val()!="" && $("#rateItemTable tr").length >= 1)
				{				
					$('#rateItemTable tr:last').after(templateClone);
					$('#rateItemTable tr:last').find(".code-name").focus();
				}
				else{
					if($("#rateItemTable tr:last th").length > 0){
						$('#rateItemTable tr:last').after(templateClone);
						$('#rateItemTable tr:last').next().find(".code-name").focus();

					}
					else{
						$('#rateItemTable tr:last').before(templateClone);
						$('#rateItemTable tr:last').prev().find(".code-name").focus();

					}

					}
					
				indexField.text(index + 1);
				
				template.find(":input:eq(0)").attr("checked",false);
				$('.rtindexcheck').attr("checked",false);
				//template.find(":input:eq(1)").val("");
				//template.find(":input:eq(2)").val("");
				//template.find(":input:eq(3)").val("");
				//template.find(":input:eq(4)").val("");
				//template.find(":input:eq(5)").val("");
				//template.find(":input:eq(7)").attr("checked",true);
				//template.find(":input:eq(7)").attr("checked",false);
	       
	    }

  
  
	

   function checkDuplicateRateItemCodes(){
	  $(".userRateItems .errorHighlight").removeClass("errorHighlight");

	  var uniqueInd=true;
	  var duplCount=0;
	  var list=new Array();
	  $(".userRateItems tbody tr #rateItemCode > input").each(function() {
		  if($(this).val()==""){
			  
		  }
		  else
			  list.push($(this).val().toLowerCase());
	  });
	  
	  $.each(list, function(index, value){
		  if(value!=null){
			  if($.inArray(value.toLowerCase(), list)!=index){
				  highlightDuplicates(value.toLowerCase());
				  duplCount++;
			  }			  			
		  }
	  });
	  
	  if(duplCount>0)
		  uniqueInd = false;
	  
	  return uniqueInd;
  }
   
   function highlightDuplicates(duplCode){
	   $(".userRateItems tbody tr").each(function(index){
			 if($(this).find(".code-name").val()=="" || $(this).find(".code-name").val()==undefined){
			
				
			 }
			 else{
				 if($(this).find(".code-name").val().toLowerCase()==duplCode){
					 $(this).removeClass("heighlight");
					 $(this).addClass("errorHighlight");
				 }
			 }
			
			
			 
		 });
   }
   
   function checkDuplicateRateProfile(initials, profileType){
	   var uniqueProfileInd=true;
	   var count=0; 
	   var prfIndex=-1;
	   var ratePrfLinksStr=$("#ratePrfLinks").html();
	   var ratePrfLinksArr=ratePrfLinksStr.split(",");
	   for(var i=0; i<ratePrfLinksArr.length; i++){
		   var linkArr=ratePrfLinksArr[i].split("-");
		   if(profileType==parseInt(linkArr[0])){			 
			   if($.trim(initials).toLowerCase()==$.trim(linkArr[1]).toLowerCase()){
				   	prfIndex=linkArr[2];
					count++;
			   }
		   }
	   }
	  
	   var curPrfIndex=-1;
	   var rtId= $("#curRTId").text();
	   if(rtId!=0)
		   curPrfIndex=$("#rtprf"+rtId).text();
	 
	   
	   if(curPrfIndex!=-1){
		   if(parseInt(prfIndex)==parseInt(curPrfIndex)){
			   if(count>1){
				   uniqueProfileInd=false;
				   return uniqueProfileInd;
			   }	   
		   }
		   else{
			   if(count>0){
				   uniqueProfileInd=false;
				   return uniqueProfileInd;
			   }
		   }
	   }
	   else{
		   if(count>0){
			   uniqueProfileInd=false;
			   return uniqueProfileInd;
		   }
	   }
	  
	   	   
	   return uniqueProfileInd;
   }
  
function refreshExpediteOptionsList(){
	var expCount=0;
	 $(".userRateItems tbody tr").each(function(index){
		 if($(this).find(".price-type-id").val()==2){
			 expCount++;
		 }				
	 });
	 if(expCount>0){
	    	//console.log("all options change");

		 newRateItemsList=[];
		 existingRateItemsList=[];
		 $(".userRateItems tbody tr").each(function(index){
			 if($(this).find(".price-type-id").val()!=2){
				 if($(this).prev().val()=="" || $(this).prev().val()=="0"){
					 var newRateItemCode=$(this).find(".code-name").val();
					 var newRowIdx=$(this).find(".code-name").attr("id");
					 if(newRateItemCode!=""){
						 var newRtItem={
							id: -newRowIdx,
							type: newRateItemCode
						 };
						 newRateItemsList.push(newRtItem); 
					 }
				 }
			 }				
		 });
		
		 var curRowPriceType;
		 var slctIndex;
		 
		 $(".userRateItems tbody tr").each(function(index){
			 curRowPriceType=$(this).find(".price-type-id").val();
			 if(curRowPriceType==2){
				 slctIndex=$(this).find(".rate-item-list option:selected").val();
				 $(this).find(".rate-item-list").empty();
				 for(var k = 0 ; k < expeditTypeslist.length ; k++){
					 if($(this).find(".code-name").val()!=expeditTypeslist[k].type)
						 $(this).find(".rate-item-list").append("<option value='"+expeditTypeslist[k].id+"'>"+expeditTypeslist[k].type+"</option>");
					 						 
		         }
				 for(var j = 0 ; j < newRateItemsList.length ; j++){
					 if(newRateItemsList[j].type!=$(this).find(".code-name").val()){
						 $(this).find(".rate-item-list").append("<option value='"+newRateItemsList[j].id+"'>"+newRateItemsList[j].type+"</option>");							
					 }
				 }
				 $(this).find(".rate-item-list option").each(function(){
			        if($(this).val()==slctIndex){ 
			            $(this).attr("selected","selected");    
			        }
			    });
			 } 
		 });		
	 }		 	
}	

function checkPayPeriodDuplicates(ispopup){
	var uniquePayInd=true;
	var payArray = new Array();
	var payOtherArray=new Array();
	
	$(".payday").each(function(i){		
		var turnInVal=$(this).val();
		var turnInOtherVal="";
		var delInd=$(this).parent().parent().next().find(".delete-input").val();
		
		if(turnInVal==5){
		
			if(delInd=="false"){
				turnInOtherVal=$(this).closest(".userdetailsformcolum").find(".turnInOther").val();
				payOtherArray.push(turnInOtherVal);
			}
		}
		else{
			if($(this).is(':visible'))
				payArray.push(turnInVal);
		}		
			
	});	
	
	payArray.pop();
	
	var resultOtherArray = removeDuplicateElement(payOtherArray);
	var resultArray = removeDuplicateElement(payArray);	
	
	Array.prototype.contains = function(k) {
		
	    for(p in this)
	        if(this[p] === k)
			{
	            return true;
			}
	    return false;
	}
	
	var result = resultArray.contains("2");
	var resultOther = resultOtherArray.contains("1");
	var result1 = resultArray.contains("3");
	var resultOther1 = resultOtherArray.contains("15");

		if(payArray.length != resultArray.length || payOtherArray.length != resultOtherArray.length){
			$("#ui-tips").text("Specify unique Turn In Cut Off Day").addClass( "ui-state-highlight" );
			
			if(ispopup)
			$("#rateTableForm").animate({scrollTop: $("#ui-tips").offset().top}, "slow");
			
	  		$('html, body').animate({ scrollTop: $("#ui-tips").offset().top }, "slow");
	  		uniquePayInd=false;
		}			
		else if(result == true && resultOther == true)
		{
			$("#ui-tips").text("Specify unique Turn In Cut Off Day").addClass( "ui-state-highlight" );
			
			if(ispopup)
			$("#rateTableForm").animate({scrollTop: $("#ui-tips").offset().top}, "slow");
			
	  		$('html, body').animate({ scrollTop: $("#ui-tips").offset().top }, "slow");		
	  		uniquePayInd=false;	
		}
		else if(result1 == true && resultOther1 == true)
		{
			$("#ui-tips").text("Specify unique Turn In Cut Off Day").addClass( "ui-state-highlight" );
			
			if(ispopup)
			$("#rateTableForm").animate({scrollTop: $("#ui-tips").offset().top}, "slow");
			
	  		$('html, body').animate({ scrollTop: $("#ui-tips").offset().top }, "slow");	
	  		uniquePayInd=false;
		}
		else{
			$("#ui-tips").text("").removeClass("ui-state-highlight");
			uniquePayInd=true;
		}
		return uniquePayInd;
} 

function highlightCheckedRows(){
	 $(".userRateItems tbody tr").each(function(index){
		 if($(this).find(".rtindexcheck").is(":checked"))
			 $(this).addClass("heighlight");
	 });	 
}


		